package org.example.common;

import org.example.tcp.TcpData;

import java.io.*;

public class MyConverter {
    public static byte[] toByteArray(TcpData tcpData) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(tcpData);
        objectOutputStream.flush();
        byte[] bytes = byteArrayOutputStream.toByteArray();
        objectOutputStream.close();
        byteArrayOutputStream.close();
        return bytes;
    }
    public static TcpData fromByteArray(byte[] bytes) throws IOException, ClassNotFoundException {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        TcpData tcpData = (TcpData) objectInputStream.readObject();
        objectInputStream.close();
        byteArrayInputStream.close();

        // 返回一个新的对象
        return tcpData;
    }
}
